import hashlib
import json
import hashlib
#导入原生sql模块
from django.db import connection

import re
from django.shortcuts import render,redirect


from mydjango.settings import SECRET_KEY
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io
from django.http import HttpResponse
from django.views import View
from myapp.myser import Courserlizer
from myapp.models import *
from rest_framework.views import APIView
import os

from mydjango.settings import UPLOAD_ROOT

class Courselist(APIView):
    def get(self,request):
        #当前页
        page = request.GET.get('page',1)
        #每页展示条数
        size = request.GET.get('size',1)
        #开始位置
        data_start = (int(page)-1 * int(size))
        #结束位置
        data_end = int(page) * int(size)
        #查询
        courselist = Course.objects.all()[data_start:data_end]
        #总条数
        count = Course.objects.count()
        #序列化
        courselist_list = Courserlizer(courselist,many=True)
        return Response({'data':courselist_list.data,'total':count})

    def post(self, request):
        title = request.data.get('title')
        desc = request.data.get('desc')
        price = request.data.get('price')
        video = request.data.get('video')
        cid = request.data.get('cid')
        Course.objects.create(title=title, desc=desc, price=price, video=video, cid_id=cid)
        return Response({'msg': '添加课程成功', 'code': 200})

    #构造课程分类层级关系
def get_tree(data):

        lists = []
        tree = {}

        for item in data:
            tree[item['id']] = item
        for i in data:
            if not i['pid']:
                lists.append(tree[i['id']])
            else:
                parent_id = i['pid']
                if 'children' not in tree[parent_id]:
                    tree[parent_id]['children'] = []
                tree[parent_id]['children'].append(tree[i['id']])
        return  lists









def dictfetchall(cursor):

    desc = cursor.description

    return [

        dict(zip([col[0] for col in desc],row))

        for row in cursor.fetchall()

    ]
from myapp.models import *
#zip方法合并list中的 key 和 value
#从第一个数据开始循环




def get_cate(request) :
    curosr = connection.cursor()
    curosr.execute( 'SELECT * from cate')
    res = dictfetchall(curosr)
    res = get_tree(res)
    return HttpResponse(json.dumps(res,indent=4,ensure_ascii=False),content_type='application/joson')


class AddCouse(APIView):
    def get(self,request):
        title = request.GET.get('title',None)
        desc = request.GET.get('desc')
        price = request.GET.get('price',None)
        video = request.GET.get('video')
        cid = request.GET.get('cid',None)
        course = Course(title=title,desc=desc,price=price,video=video,cid=cid)
        course.save()
        return  Response({'code':200,'msg':'提交课程成功'})








#获取某个用户的权限
class GetUserAccess(View):
    def get(self,request):
        uid = request.GET.get('uid',None)
        cursor = connection.cursor()
        cursor.execute('SELECT a.username,c.node_name,c.id from user a left join access b on a.id=b.uid left join node c on b.node_id = c.id where a.id =%s;' % uid)
        #获取结果集
        # res = cursor.fetchall()

        res = dictfetchall(cursor)

        return HttpResponse(json.dumps(res,indent=4,ensure_ascii=False),content_type='application/json')
# indent缩进4个空格
user = 0b110
permission = 0b001

def my_decorator(func):
    def wrapper(request,*args,**kwargs):
        print('装饰器被调用')
        if user & permission:
            return func(request,*args,**kwargs)
        else:
            return HttpResponse('您没有权限')
    return wrapper
def upload_img(request):
    return HttpResponse('上传成功')

class Courses(APIView):
    def get(self,request):
        cid = request.GET.get('cid')
        queryset = Course.objects.filter(id = cid)
        ser = Courserlizer(queryset,many=True)
        return Response(ser.data)





def make_password(mypass):
    # 生成对象
    md5 = hashlib.md5()
    # 定义加密对象
    sign_str = mypass
    # 转码
    sign_utf8 = str(sign_str).encode(encoding='utf-8')
    # 加密
    md5.update(sign_utf8)
    # 生成密文
    md5_server = md5.hexdigest()

    return md5_server


class Ding_On(APIView):
    def post(self,request):
        username = request.data.get('username')
        DingUser.objects.get(username = username)
        return Response({"msg":'登陆成功','code':200})

# class MyCode(View):
#
#     # 内置类方法
#     def get_random_color(self):
#         # 三原色取色R,G,B
#         R = random.randrange(255)
#         G = random.randrange(255)
#         B = random.randrange(255)
#
#         return (R,G,B)

    # def get(self,request):
    #
    #     # 定义画布
    #     img_sizi = (120,50)
    #
    #     # 定义图像对象
    #     image = Image.new('RGB',img_sizi,'white')
    #     # 定义画笔
    #     draw = ImageDraw.Draw(image,'RGB')
    #     # 定义字符串
    #     source = 'peekaboo'
    #     # 定义容器
    #     code_str = ''
    #
    #     for i in range(4):
    #         # 获取字符颜色
    #         text_color = self.get_random_color()
    #         # 获取随机字符
    #         tmp_num = random.randrange(len(source))
    #         random_str = source[tmp_num]
    #         code_str += random_str
    #
    #         draw.text((10+30*i,20),random_str,text_color)
    #
    #     buf = io.BytesIO()
    #     image.save(buf,'png')
    #
    #     # 保存验证码,将验证码保存在session中
    #     request.session['code'] = code_str
    #
    #     return HttpResponse (buf.getvalue(),'image/png')



#上传图片接口
class Uploader(View):
	def post(self,request):
        #接受文件
		file = request.FILES.get('file')
        #写文件
		with open(os.path.join(UPLOAD_ROOT,'',file.name),'wb') as f:
			for chunk in file.chunks():
				f.write(chunk)

		return HttpResponse(json.dumps({'filename':file.name},ensure_ascii=False),content_type='application/json')


class Dwon(APIView):
    def put(self,request):
        file = request.FILES.get('file')
        uid = request.data.get('uid')
        user = User.objects.get(id = uid)
        user.img = file
        user.save()
        return Response({'上传成功'})


class Chuan(APIView):
    def put(self,request):
        uid = request.data.get('uid')
        user = User.objects.filter(id=uid).update(img = None)
        os.remove(user.img)
        print(user.img)
        return Response({'msg':'删除成功','code':200})





